<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-fill-left.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Python," />





  <link rel="alternate" href="/atom.xml" title="我的笔记本" type="application/atom+xml" />






<meta name="description" content="导读因为研究生生涯开始了，所以需要暂时停掉Java的学习，开始使用Python的学习和实践了。于是花了一个小时从完全没学过到实现了最基础的单链表。这里就记录一下。">
<meta property="og:type" content="article">
<meta property="og:title" content="python基础综合：链表">
<meta property="og:url" content="https://sakebow.github.io/2020/08/17/python/%E8%80%81%E5%85%B5%E6%96%B0%E7%BB%83/python%E5%9F%BA%E7%A1%80%E7%BB%BC%E5%90%88%EF%BC%9A%E9%93%BE%E8%A1%A8/index.html">
<meta property="og:site_name" content="我的笔记本">
<meta property="og:description" content="导读因为研究生生涯开始了，所以需要暂时停掉Java的学习，开始使用Python的学习和实践了。于是花了一个小时从完全没学过到实现了最基础的单链表。这里就记录一下。">
<meta property="article:published_time" content="2020-08-17T14:00:00.000Z">
<meta property="article:modified_time" content="2020-11-01T15:28:31.876Z">
<meta property="article:author" content="sakebow">
<meta property="article:tag" content="Python">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://sakebow.github.io/2020/08/17/python/老兵新练/python基础综合：链表/"/>



<meta name="google-site-verification" content="gmKmVpWaqN85ipDFNNCd2AweYJjcTFrVxCKCy36wueo" />
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?1d2c90caa02c073d8ebaa116ab3027fb";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>


  <title>python基础综合：链表 | 我的笔记本</title>
  








  
  <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
  <script type="text/javascript" src="/js/src/custom.js"></script>
  
<meta name="generator" content="Hexo 4.2.1"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
	
	<a href="https://github.com/sakebow" target="_blank" rel="noopener" class="github-corner" aria-label="View source on GitHub">
	  <svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"
	    style="fill:#64CEAA; color:#fff; position: fixed; top: 0; border: 0; right: 0; z-index: 999;">
	    <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
		<path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
		  fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
		<path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
		  fill="currentColor" class="octo-body"></path>
	  </svg>
	</a>
	<style>
	  .github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}
	  @keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}
	  @media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}
	</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">我的笔记本</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一只干什么都会失败但是很不想放弃的科研狗</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://sakebow.github.io/2020/08/17/python/%E8%80%81%E5%85%B5%E6%96%B0%E7%BB%83/python%E5%9F%BA%E7%A1%80%E7%BB%BC%E5%90%88%EF%BC%9A%E9%93%BE%E8%A1%A8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="sakebow">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/icon/UN.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="我的笔记本">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">python基础综合：链表</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-08-17T22:00:00+08:00">
                2020-08-17
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80%E7%BB%BC%E5%90%88%E6%B5%8B%E9%AA%8C/" itemprop="url" rel="index">
                    <span itemprop="name">编程基础综合测验</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2020/08/17/python/%E8%80%81%E5%85%B5%E6%96%B0%E7%BB%83/python%E5%9F%BA%E7%A1%80%E7%BB%BC%E5%90%88%EF%BC%9A%E9%93%BE%E8%A1%A8/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count gitment-comments-count" data-xid="/2020/08/17/python/%E8%80%81%E5%85%B5%E6%96%B0%E7%BB%83/python%E5%9F%BA%E7%A1%80%E7%BB%BC%E5%90%88%EF%BC%9A%E9%93%BE%E8%A1%A8/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3k字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  12分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="导读"><a href="#导读" class="headerlink" title="导读"></a>导读</h2><p><strong>因为研究生生涯开始了，所以需要暂时停掉<code>Java</code>的学习，开始使用<code>Python</code>的学习和实践了。于是花了一个小时从完全没学过到实现了最基础的单链表。这里就记录一下。</strong></p>
<a id="more"></a>
<h2 id="链表结构复习"><a href="#链表结构复习" class="headerlink" title="链表结构复习"></a>链表结构复习</h2><p>首先我们回顾链表由什么构成。在<code>C</code>语言中，对链表的定义就是：</p>
<blockquote>
<p>链表是一种动态数据结构。它主要是利用动态内存分配、使用结构体并配合之镇来实现的一种数据结构。</p>
<p>——摘自《C语言程序设计（第三版）》苏小红、王宇颖、孙志岗等编著</p>
</blockquote>
<p>也就是说，链表有以下几个特点：</p>
<ul>
<li><p>是类似数组的链式结构</p>
</li>
<li><p>内存分配并不像数组一样完全连续</p>
</li>
<li><p>每个节点使用结构体，每个节点也就有了更高的自由度和更大的存储量</p>
</li>
<li><p>下一个节点的位置保存在上一个节点中</p>
</li>
</ul>
<h2 id="Python对比预习"><a href="#Python对比预习" class="headerlink" title="Python对比预习"></a><code>Python</code>对比预习</h2><p>复习了链表之后，让我们再看看<code>Python</code>语言相对于<code>C</code>语言和<code>Java</code>有什么不同：</p>
<ul>
<li><p>不需要显式声明<code>private</code>、<code>protected</code>和<code>public</code></p>
</li>
<li><p>对象名直接对应对象的地址，这一点和<code>Java</code>非常相似</p>
</li>
<li><p>没有括号限制函数体，直接用缩进表示</p>
</li>
<li><p><code>None</code>对应<code>C</code>语言和<code>Java</code>的<code>null</code></p>
</li>
<li><p><code>self</code>代替了<code>C</code>语言和<code>Java</code>的<code>this</code>指针</p>
</li>
<li><p>魔法函数<code>__init__</code>直接定义了结构体的属性构成，而不需要显式定义结构体具体有哪些属性</p>
</li>
</ul>
<p>主要就是这些了。具体的细节我们遇到了再去查<a href="https://www.runoob.com/python3/python3-tutorial.html" target="_blank" rel="noopener"><strong>菜鸟教程</strong></a>就好了。当然，如果能够直接查<a href="https://docs.python.org/zh-cn/3/" target="_blank" rel="noopener"><code>Python</code></a>官方文档更好，毕竟都贴心地给出了中文版（但是点进去每个函数的解释还是<strong>英文</strong>，而且没有实例）。</p>
<h2 id="从节点的定义开始编码"><a href="#从节点的定义开始编码" class="headerlink" title="从节点的定义开始编码"></a>从节点的定义开始编码</h2><p>那么，为了先熟悉<code>Python</code>的语法，我们先来个小小的结构体试试水：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># -*- coding: UTF-8 -*-</span></span><br><span class="line"><span class="comment"># 链表节点</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Node</span>:</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, data, next, index)</span>:</span></span><br><span class="line">    self.data = data</span><br><span class="line">    self.next = next</span><br><span class="line">    self.index = index</span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">  <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 测试节点</span></span><br><span class="line">node = Node(<span class="number">0</span>, <span class="literal">None</span>, <span class="number">0</span>)</span><br><span class="line">print(node.data)</span><br></pre></td></tr></table></figure>
<p>当然，没有悬念，输出<code>0</code>。</p>
<p>第一行首先是确认字符编码。默认是<code>UTF-8</code>，根据需要可以更换成别的；其次是使用<code>__init__</code>函数定义一个具有三个属性的类作为结构体；最后的pass则是占位符，表示一个域的结束，相当于<code>}</code>。因为<code>Python</code>直接使用缩进表示是否结束，所以这个仅仅作为个人习惯出现在这里。</p>
<h2 id="从链表的功能开始完善"><a href="#从链表的功能开始完善" class="headerlink" title="从链表的功能开始完善"></a>从链表的功能开始完善</h2><p>既然我们完成了节点的构造，那么我们一口气把整个链表攻下来吧！</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 链表</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Link</span>:</span></span><br><span class="line">  <span class="comment"># 初始化 / 不需要参数，自带空的头节点</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">    self.head = <span class="literal">None</span></span><br><span class="line">    self.length = <span class="number">0</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">  <span class="comment"># 尾插法插入数据</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">insert_tail</span><span class="params">(self, index, data)</span>:</span></span><br><span class="line">    <span class="comment"># 当尾节点为空时，使用头插法确定尾节点</span></span><br><span class="line">    <span class="keyword">if</span> self.tail <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">      self.insert_head(index, data)</span><br><span class="line">      <span class="keyword">pass</span></span><br><span class="line">    <span class="comment"># 在尾节点非空时往后接节点</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">      node = Node(data, <span class="literal">None</span>, index)</span><br><span class="line">      self.tail.next = node</span><br><span class="line">      self.tail = node</span><br><span class="line">      <span class="keyword">pass</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">  <span class="comment"># 头插法插入数据</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">insert_head</span><span class="params">(self, index, data)</span>:</span></span><br><span class="line">    node = Node(data, self.head, index)</span><br><span class="line">    self.head = node</span><br><span class="line">    self.length += <span class="number">1</span></span><br><span class="line">    <span class="comment"># 当只有一个元素的时候，确定尾节点</span></span><br><span class="line">    <span class="keyword">if</span> self.length == <span class="number">1</span>:</span><br><span class="line">      self.tail = node</span><br><span class="line">      <span class="keyword">pass</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">  <span class="comment"># 输出链表 / 从头开始顺序输出</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">output</span><span class="params">(self)</span>:</span></span><br><span class="line">    node = self.head</span><br><span class="line">    <span class="keyword">while</span> node <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">      print(<span class="string">f'<span class="subst">&#123;node.index&#125;</span>: <span class="subst">&#123;node.data&#125;</span>'</span>, end = <span class="string">' '</span>)</span><br><span class="line">      node = node.next</span><br><span class="line">      <span class="keyword">pass</span></span><br><span class="line">    print()</span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">  <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line">link = Link()</span><br><span class="line">link.insert_head(<span class="number">1</span>, <span class="number">2</span>)</span><br><span class="line">link.insert_tail(<span class="number">3</span>, <span class="number">4</span>)</span><br><span class="line">link.output()</span><br></pre></td></tr></table></figure>
<p>在这里的<code>self</code>关键字在<strong>函数体内</strong>就是<strong>作为<code>this</code>指针</strong>使用，而作为<strong>参数</strong>出现的时候就是声明该函数是一个<strong>成员函数</strong>。后面有一句：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">print(<span class="string">f'<span class="subst">&#123;node.index&#125;</span>: <span class="subst">&#123;node.data&#125;</span>'</span>, end = <span class="string">' '</span>)</span><br></pre></td></tr></table></figure>
<p>这是<code>Python</code>3.6以后的新特性，使用<code>f</code>直接将字符串格式化，另外使用<code>end</code>规定输出结尾是空格而不是默认的换行结尾。</p>
<p>于是，这次的输出就是：<code>1:2 3:4</code>。</p>
<h2 id="全自动构造链表"><a href="#全自动构造链表" class="headerlink" title="全自动构造链表"></a>全自动构造链表</h2><p>但是这还差一个输入。不想一个字一个字输入的我直接定义了一个随机生成的函数，让链表自己随便生成什么东西。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 文件开头加上：</span></span><br><span class="line"><span class="keyword">import</span> random</span><br><span class="line">LETTERS = <span class="string">'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'</span></span><br><span class="line">LETTERS_LEN = len(LETTERS)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 在Link类中添加成员函数</span></span><br><span class="line"><span class="comment"># 随机生成链表</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">random_link</span><span class="params">(self)</span>:</span></span><br><span class="line">  size = random.randint(<span class="number">0</span>, <span class="number">20</span>)</span><br><span class="line">  <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">0</span>, size):</span><br><span class="line">    self.insert_tail(i + <span class="number">1</span>, LETTERS[random.randint(<span class="number">0</span>, LETTERS_LEN - <span class="number">1</span>)])</span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">  <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 全自动生成</span></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">  link = Link()</span><br><span class="line">  link.random_link()</span><br><span class="line">  link.output()</span><br><span class="line">  <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<p>于是每次编译输出都有完全不一样的结果。</p>
<p>好了，到这里构造链表就没有什么大问题了。</p>
<h2 id="删除节点"><a href="#删除节点" class="headerlink" title="删除节点"></a>删除节点</h2><p>接下来就是很恼人的删除节点了。和<code>C++</code>一样，可以直接使用<code>del</code>命令显式删除对象。值得一提的是，这里显式删除之后只是将内存标记为“<strong>可使用</strong>”，该部分内存并没有被回收。之后<code>GC</code>会过来打扫的。</p>
<p>为了能够保持数组每次都是一致的，方便查看位置，这里添加了文件读取，能够在每次运行的时候从<code>linklist.csv</code>中读取一模一样的数据。</p>
<p>数据文件<code>linklist.csv</code>：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">a</span><br><span class="line">b</span><br><span class="line">3</span><br><span class="line">1000</span><br><span class="line">7</span><br><span class="line">p</span><br><span class="line">q</span><br><span class="line">h</span><br><span class="line">@</span><br><span class="line">!</span><br><span class="line">,</span><br><span class="line">&gt;</span><br><span class="line">shift</span><br></pre></td></tr></table></figure>
<p>然后是读取文件并删掉<code>readline</code>方法读取时最后的字符<code>\n</code>误读的情况：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 读取固定的链表</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">read_file</span><span class="params">(self, filepath)</span>:</span></span><br><span class="line">  index = <span class="number">1</span></span><br><span class="line">  <span class="keyword">with</span> open(filepath, <span class="string">'r'</span>) <span class="keyword">as</span> lines:</span><br><span class="line">    <span class="keyword">for</span> line <span class="keyword">in</span> lines:</span><br><span class="line">      self.insert_tail(index, line.rstrip(<span class="string">'\n'</span>))</span><br><span class="line">      index += <span class="number">1</span></span><br><span class="line">      <span class="keyword">pass</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">  <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<p>接着是删除某个位置的节点。这里虽然没有难点，但是很难在细节上保持平衡。需要考虑以下几种情况：</p>
<ul>
<li><p>链表<strong>没有节点</strong></p>
</li>
<li><p>链表<strong>有且仅有</strong>一个节点</p>
</li>
<li><p>中间<strong>任意位置</strong>删除</p>
</li>
<li><p>要删除的是<strong>第一个元素</strong></p>
</li>
<li><p>要删除的是<strong>最后一个元素</strong></p>
</li>
</ul>
<p>如果面面俱到，代码一定会纷繁复杂。所以我们需要根据这些非常神奇的地方巧妙避雷：</p>
<ul>
<li><p>如果链表没有节点，<strong>直接结束</strong></p>
</li>
<li><p>如果链表仅一个节点，删除时需要同时解除<code>head</code>指针、<code>tail</code>指针，<strong>避免指针指了个寂寞</strong>，然后一脸哀怨的给你报了个错</p>
</li>
<li><p>在删除的时候，使用临时指针<code>node</code>指向<code>head</code>指针或者<code>tail</code>指针，并删除<code>node</code>指针的时候，你会发现<code>head</code>和<code>tail</code>实际指向的地址依然存在原有的实例对象。所以实际步骤应当是<strong>先重置原先指向需要删除地址的指针，再删除临时指针</strong></p>
</li>
<li><p>删除的时候需要在最后修改链表长度，避免下次使用的时候<strong>索引超限</strong></p>
</li>
</ul>
<h2 id="删除节点实现"><a href="#删除节点实现" class="headerlink" title="删除节点实现"></a>删除节点实现</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 使用索引删除节点</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">delete_node_by_index</span><span class="params">(self, index)</span>:</span></span><br><span class="line">  <span class="comment"># 没有节点</span></span><br><span class="line">  <span class="keyword">if</span> self.head <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">    <span class="keyword">return</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">  <span class="comment"># 删除头</span></span><br><span class="line">  <span class="keyword">elif</span> index == <span class="number">1</span>:</span><br><span class="line">    node = self.head</span><br><span class="line">    self.head = self.head.next</span><br><span class="line">    <span class="keyword">del</span> node</span><br><span class="line">    <span class="comment"># 检查是不是只有这个节点</span></span><br><span class="line">    <span class="comment"># 如果无视tail，head将会为None而tail保持原样</span></span><br><span class="line">    <span class="keyword">if</span> self.head <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">      self.tail = self.head</span><br><span class="line">      <span class="keyword">pass</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">  <span class="comment"># 中间任意位置删除</span></span><br><span class="line">  <span class="keyword">else</span>:</span><br><span class="line">    node = self.get_node(index - <span class="number">1</span>)</span><br><span class="line">    temp = node.next</span><br><span class="line">    <span class="keyword">if</span> temp <span class="keyword">is</span> self.tail:</span><br><span class="line">      node.next = <span class="literal">None</span></span><br><span class="line">      self.tail = node</span><br><span class="line">      <span class="keyword">del</span> temp</span><br><span class="line">      <span class="keyword">pass</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">      node.next = temp.next</span><br><span class="line">      <span class="keyword">del</span> temp</span><br><span class="line">      <span class="keyword">pass</span></span><br><span class="line">    <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<p>然后我们来测试一下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 测试删除是否成功</span></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">  link = Link()</span><br><span class="line">  link.read_file(<span class="string">'/home/sakebow/python/linklist/linklist.csv'</span>)</span><br><span class="line">  link.delete_node_by_index(link.length)</span><br><span class="line">  link.output()</span><br><span class="line">  <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<p>这里要强调的是<code>read_file</code>命令需要<strong>完整的绝对路径</strong>，否则无法读取文件。</p>
<p>当然，很完美地删掉了最后一个元素：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">1: 1 2: 2 3: 3 4: 10 5: 11 6: a 7: b 8: 3 9: 1000 10: 7 11: p 12: q 13: h 14: @ 15: ! 16: , 17: &gt;</span><br></pre></td></tr></table></figure>
<h2 id="删除节点进阶"><a href="#删除节点进阶" class="headerlink" title="删除节点进阶"></a>删除节点进阶</h2><p>接着我们再来完善匹配所有项的方法：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 匹配内容删除节点</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">delete_node_by_data</span><span class="params">(self, data)</span>:</span></span><br><span class="line">  <span class="comment"># 强行改为有头节点的链表 / 内容随意，仅需保证next指向head</span></span><br><span class="line">  node = Node(<span class="string">'a'</span>, self.head, <span class="number">0</span>)</span><br><span class="line">  <span class="comment"># 保持标识，最后需要删除</span></span><br><span class="line">  <span class="comment"># 如果head移动了也不要紧，node将会控制下一跳的位置</span></span><br><span class="line">  stay_head = node</span><br><span class="line">  <span class="comment"># 游标，规定temp为必删项，node为上一项</span></span><br><span class="line">  temp = self.head</span><br><span class="line">  <span class="comment"># 遍历链表</span></span><br><span class="line">  <span class="keyword">while</span> temp <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">    <span class="comment"># 如果要删第一个</span></span><br><span class="line">    <span class="keyword">if</span> temp <span class="keyword">is</span> self.head <span class="keyword">and</span> temp.data == data:</span><br><span class="line">      <span class="comment"># 先重置</span></span><br><span class="line">      node.next = temp.next</span><br><span class="line">      <span class="comment"># 检查tail</span></span><br><span class="line">      <span class="keyword">if</span> temp <span class="keyword">is</span> self.tail:</span><br><span class="line">        self.tail = self.head = node.next</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line">      <span class="comment"># 再删除</span></span><br><span class="line">      <span class="keyword">del</span> temp</span><br><span class="line">      <span class="comment"># 因为下次循环依然需要使用temp，所以重置为node下一跳</span></span><br><span class="line">      temp = node.next</span><br><span class="line">      <span class="comment"># 修改长度</span></span><br><span class="line">      self.length -= <span class="number">1</span></span><br><span class="line">      <span class="keyword">pass</span></span><br><span class="line">    <span class="comment"># 中间任意项删除</span></span><br><span class="line">    <span class="comment"># 原理同上</span></span><br><span class="line">    <span class="keyword">elif</span> temp <span class="keyword">is</span> <span class="keyword">not</span> self.head <span class="keyword">and</span> temp.data == data:</span><br><span class="line">      node.next = temp.next</span><br><span class="line">      <span class="keyword">if</span> temp <span class="keyword">is</span> self.tail:</span><br><span class="line">        self.tail = node</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line">      <span class="keyword">del</span> temp</span><br><span class="line">      temp = node.next</span><br><span class="line">      self.length -= <span class="number">1</span></span><br><span class="line">      <span class="keyword">pass</span></span><br><span class="line">    <span class="comment"># 如果不匹配，全部下一跳，且长度不变</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">      temp = temp.next</span><br><span class="line">      node = node.next</span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">  <span class="comment"># 最终删除辅助节点</span></span><br><span class="line">  <span class="keyword">del</span> stay_head</span><br><span class="line">  <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<p>那我们来测试一下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">  link = Link()</span><br><span class="line">  link.read_file(<span class="string">'/home/sakebow/python/linklist/linklist.csv'</span>)</span><br><span class="line">  <span class="comment"># 因为数据集里面3出现了两次，所以选择3</span></span><br><span class="line">  link.delete_node_by_data(<span class="string">'3'</span>)</span><br><span class="line">  link.output()</span><br><span class="line">  <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<p>当然，最终结果把两个3全部删掉了：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">1: 1 2: 2 4: 10 5: 11 6: a 7: b 9: 1000 10: 7 11: p 12: q 13: h 14: @ 15: ! 16: , 17: &gt; 18: shift</span><br></pre></td></tr></table></figure>
<p>也没有问题！</p>
<p>当然你也可以使用各种各样的数据测试。就算是60万行数据也能用$1’32’’$秒给出答案。（<em>实际测量可能和电脑运算能力有误差</em>）</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>最后，为了代码简洁、项目结构清晰，我们将各个部分拆开。这里贴上各个部分的文件内容：</p>
<h3 id="Node-py"><a href="#Node-py" class="headerlink" title="Node.py"></a>Node.py</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 链表节点</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Node</span>:</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, data, next, index)</span>:</span></span><br><span class="line">    self.data = data</span><br><span class="line">    self.next = next</span><br><span class="line">    self.index = index</span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">  <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<h3 id="Link-py"><a href="#Link-py" class="headerlink" title="Link.py"></a>Link.py</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> Node <span class="keyword">import</span> *</span><br><span class="line"><span class="comment"># 链表</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Link</span>:</span></span><br><span class="line">  <span class="comment"># 初始化 / 不需要参数，自带空的头节点</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">    self.head = <span class="literal">None</span></span><br><span class="line">    self.tail = <span class="literal">None</span></span><br><span class="line">    self.length = <span class="number">0</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line">  <span class="comment"># 尾插法插入数据</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">insert_tail</span><span class="params">(self, index, data)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> self.tail <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">      self.insert_head(index, data)</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">      node = Node(data, <span class="literal">None</span>, index)</span><br><span class="line">      self.tail.next = node</span><br><span class="line">      self.tail = node</span><br><span class="line">      self.length += <span class="number">1</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">  </span><br><span class="line">  <span class="comment"># 头插法插入数据 </span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">insert_head</span><span class="params">(self, index, data)</span>:</span></span><br><span class="line">    node = Node(data, self.head, index)</span><br><span class="line">    self.head = node</span><br><span class="line">    self.length += <span class="number">1</span></span><br><span class="line">    <span class="comment"># 当只有一个元素的时候，确定尾节点</span></span><br><span class="line">    <span class="keyword">if</span> self.length == <span class="number">1</span>:</span><br><span class="line">      self.tail = node</span><br><span class="line">      <span class="keyword">pass</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">  </span><br><span class="line">  <span class="comment"># 输出链表</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">output</span><span class="params">(self)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> self.head <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">      print(<span class="string">'Nothing'</span>)</span><br><span class="line">      <span class="keyword">return</span></span><br><span class="line">      <span class="keyword">pass</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">      node = self.head</span><br><span class="line">      <span class="keyword">while</span> node <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">        print(<span class="string">f'<span class="subst">&#123;node.index&#125;</span>: <span class="subst">&#123;node.data&#125;</span>'</span>, end=<span class="string">' '</span>)</span><br><span class="line">        node = node.next</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line">      print()</span><br><span class="line">      <span class="keyword">pass</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">  </span><br><span class="line">  <span class="comment"># 随机生成链表</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">random_link</span><span class="params">(self)</span>:</span></span><br><span class="line">    size = random.randint(<span class="number">0</span>, <span class="number">20</span>)</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">0</span>, size):</span><br><span class="line">      self.insert_tail(i + <span class="number">1</span>, LETTERS[random.randint(<span class="number">0</span>, LETTERS_LEN - <span class="number">1</span>)])</span><br><span class="line">      <span class="keyword">pass</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">  </span><br><span class="line">  <span class="comment"># 读取固定的链表</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">read_file</span><span class="params">(self, filepath)</span>:</span></span><br><span class="line">    index = <span class="number">1</span></span><br><span class="line">    <span class="keyword">with</span> open(filepath, <span class="string">'r'</span>) <span class="keyword">as</span> lines:</span><br><span class="line">      <span class="keyword">for</span> line <span class="keyword">in</span> lines:</span><br><span class="line">        self.insert_tail(index, line.rstrip(<span class="string">'\n'</span>))</span><br><span class="line">        index += <span class="number">1</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line">      <span class="keyword">pass</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">  </span><br><span class="line">  <span class="comment"># 通过索引获得指定节点</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">get_node</span><span class="params">(self, index)</span>:</span></span><br><span class="line">    node = self.head</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">1</span>, index):</span><br><span class="line">      node = node.next</span><br><span class="line">      <span class="keyword">pass</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">    <span class="keyword">return</span> node</span><br><span class="line">  </span><br><span class="line">  <span class="comment"># 匹配内容删除节点</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">delete_node_by_data</span><span class="params">(self, data)</span>:</span></span><br><span class="line">    <span class="comment"># 强行改为有头节点的链表</span></span><br><span class="line">    node = Node(<span class="string">'a'</span>, self.head, <span class="number">0</span>)</span><br><span class="line">    <span class="comment"># 保持标识，最后需要删除</span></span><br><span class="line">    stayHead = node</span><br><span class="line">    <span class="comment"># 游标，规定temp为必删项，node为上一项</span></span><br><span class="line">    temp = self.head</span><br><span class="line">    <span class="keyword">while</span> temp <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">      <span class="keyword">if</span> temp <span class="keyword">is</span> self.head <span class="keyword">and</span> temp.data == data:</span><br><span class="line">        node.next = self.head = temp.next</span><br><span class="line">        <span class="keyword">if</span> temp <span class="keyword">is</span> self.tail:</span><br><span class="line">          self.tail = self.head = node.next</span><br><span class="line">          <span class="keyword">pass</span></span><br><span class="line">        <span class="keyword">del</span> temp</span><br><span class="line">        temp = node.next</span><br><span class="line">        self.length -= <span class="number">1</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line">      <span class="keyword">elif</span> temp <span class="keyword">is</span> <span class="keyword">not</span> self.head <span class="keyword">and</span> temp.data == data:</span><br><span class="line">        node.next = temp.next</span><br><span class="line">        <span class="keyword">if</span> temp <span class="keyword">is</span> self.tail:</span><br><span class="line">          self.tail = node</span><br><span class="line">          <span class="keyword">pass</span></span><br><span class="line">        <span class="keyword">del</span> temp</span><br><span class="line">        temp = node.next</span><br><span class="line">        self.length -= <span class="number">1</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line">      <span class="keyword">else</span>:</span><br><span class="line">        temp = temp.next</span><br><span class="line">        node = node.next</span><br><span class="line">      <span class="keyword">pass</span></span><br><span class="line">    <span class="keyword">del</span> stayHead</span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">  </span><br><span class="line">  <span class="comment"># 使用索引删除节点</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">delete_node_by_index</span><span class="params">(self, index)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> self.head <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">      <span class="keyword">return</span></span><br><span class="line">      <span class="keyword">pass</span></span><br><span class="line">    <span class="keyword">elif</span> index == <span class="number">1</span>:</span><br><span class="line">      node = self.head</span><br><span class="line">      self.head = self.head.next</span><br><span class="line">      <span class="keyword">if</span> self.head <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">        self.tail = self.head</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line">      <span class="keyword">pass</span></span><br><span class="line">      <span class="keyword">del</span> node</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">      node = self.get_node(index - <span class="number">1</span>)</span><br><span class="line">      temp = node.next</span><br><span class="line">      <span class="keyword">if</span> temp <span class="keyword">is</span> self.tail:</span><br><span class="line">        node.next = <span class="literal">None</span></span><br><span class="line">        self.tail = node</span><br><span class="line">        <span class="keyword">del</span> temp</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line">      <span class="keyword">else</span>:</span><br><span class="line">        node.next = temp.next</span><br><span class="line">        <span class="keyword">del</span> temp</span><br><span class="line">      <span class="keyword">pass</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">  <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<h3 id="linklist-csv"><a href="#linklist-csv" class="headerlink" title="linklist.csv"></a>linklist.csv</h3><p>这个文件后来我改得非常大，一共22932行数据，不方便展开，各位可以自行<a href="https://github.com/sakebow/python-linklist/blob/master/linklist.csv" target="_blank" rel="noopener">点击我的<code>GitHub</code></a>下载。</p>
<h3 id="linklist-py（主文件）"><a href="#linklist-py（主文件）" class="headerlink" title="linklist.py（主文件）"></a>linklist.py（主文件）</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># -*- coding: UTF-8 -*-</span></span><br><span class="line"><span class="keyword">import</span> random</span><br><span class="line"><span class="keyword">from</span> Link <span class="keyword">import</span> *</span><br><span class="line"></span><br><span class="line">LETTERS = <span class="string">'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'</span></span><br><span class="line">LETTERS_LEN = len(LETTERS)</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">  link = Link()</span><br><span class="line">  link.read_file(<span class="string">'/home/sakebow/python/linklist/linklist.csv'</span>)</span><br><span class="line">  <span class="comment"># 测试</span></span><br><span class="line">  link.delete_node_by_data(<span class="string">'3'</span>)</span><br><span class="line">  link.output()</span><br><span class="line">  <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<p>如果觉得大段大段的代码在这里看不怎么清楚的话，直接在<a href="https://github.com/sakebow/python-linklist" target="_blank" rel="noopener">我的GitHub</a>中下载也可以。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>代码滞销，救救码农</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/pay/wechatpay.png" alt="sakebow 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/pay/alipay.jpg" alt="sakebow 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    sakebow
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://sakebow.github.io/2020/08/17/python/%E8%80%81%E5%85%B5%E6%96%B0%E7%BB%83/python%E5%9F%BA%E7%A1%80%E7%BB%BC%E5%90%88%EF%BC%9A%E9%93%BE%E8%A1%A8/" title="python基础综合：链表">https://sakebow.github.io/2020/08/17/python/%E8%80%81%E5%85%B5%E6%96%B0%E7%BB%83/python%E5%9F%BA%E7%A1%80%E7%BB%BC%E5%90%88%EF%BC%9A%E9%93%BE%E8%A1%A8/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"> <i class="fa fa-tag"></i> Python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/08/06/diary/%E5%9B%9E%E8%80%81%E5%AE%B6%E7%9A%84%E5%9B%9B%E5%A4%A9%E5%81%87%E6%9C%9F/" rel="next" title="回老家的四天假期">
                <i class="fa fa-chevron-left"></i> 回老家的四天假期
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/08/20/python/%E8%80%81%E5%85%B5%E6%96%B0%E7%BB%83/python%E8%BF%9B%E9%98%B6%E8%AE%AD%E7%BB%83%EF%BC%9A%E8%81%8A%E5%A4%A9%E5%AE%A4/" rel="prev" title="python进阶训练：聊天室">
                python进阶训练：聊天室 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      
        <div onclick="showGitment()" id="gitment-display-button">显示 Gitment 评论</div>
        <div id="gitment-container" style="display:none"></div>
      
    </div>
	<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">
    <script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script>
	<script>
      var gitment = new Gitment({
        id: '<%= page.date %>',
        owner: 'sakebow',
        repo: 'git@github.com:sakebow/sakebow.github.io.git',
        oauth: {
          client_id: '5c74c5e1b67e5a5adbdf',
          client_secret: '0d352353407a32cee695d8ac619108e725919c57',
        },
      });
      gitment.render('gitment-container');
    </script>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/icon/UN.png"
                alt="sakebow" />
            
              <p class="site-author-name" itemprop="name">sakebow</p>
              <p class="site-description motion-element" itemprop="description">哪怕是狗也不想随随便便放弃看到的骨头</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%7C%7C%20archive">
              
                  <span class="site-state-item-count">70</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">21</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/sakebow" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:sakebowljx@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://plus.google.com/sakebow" target="_blank" title="Google">
                      
                        <i class="fa fa-fw fa-google"></i>Google</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://twitter.com/sakebow" target="_blank" title="Twitter">
                      
                        <i class="fa fa-fw fa-twitter"></i>Twitter</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/sakebow" title="Sakebow的GitHub" target="_blank">Sakebow的GitHub</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.appgofast.com" title="我喜欢的VPN" target="_blank">我喜欢的VPN</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#导读"><span class="nav-number">1.</span> <span class="nav-text">导读</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#链表结构复习"><span class="nav-number">2.</span> <span class="nav-text">链表结构复习</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Python对比预习"><span class="nav-number">3.</span> <span class="nav-text">Python对比预习</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#从节点的定义开始编码"><span class="nav-number">4.</span> <span class="nav-text">从节点的定义开始编码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#从链表的功能开始完善"><span class="nav-number">5.</span> <span class="nav-text">从链表的功能开始完善</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#全自动构造链表"><span class="nav-number">6.</span> <span class="nav-text">全自动构造链表</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#删除节点"><span class="nav-number">7.</span> <span class="nav-text">删除节点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#删除节点实现"><span class="nav-number">8.</span> <span class="nav-text">删除节点实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#删除节点进阶"><span class="nav-number">9.</span> <span class="nav-text">删除节点进阶</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">10.</span> <span class="nav-text">总结</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Node-py"><span class="nav-number">10.1.</span> <span class="nav-text">Node.py</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Link-py"><span class="nav-number">10.2.</span> <span class="nav-text">Link.py</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#linklist-csv"><span class="nav-number">10.3.</span> <span class="nav-text">linklist.csv</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#linklist-py（主文件）"><span class="nav-number">10.4.</span> <span class="nav-text">linklist.py（主文件）</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Sakebow</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  







<!-- LOCAL: You can save these files to your site and update links -->
    
        
        <link rel="stylesheet" href="https://aimingoo.github.io/gitmint/style/default.css">
        <script src="https://aimingoo.github.io/gitmint/dist/gitmint.browser.js"></script>
    
<!-- END LOCAL -->

    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitmint({
            id: window.location.pathname, 
            owner: 'sakebow',
            repo: 'git@github.com:sakebow/sakebow.github.io.git',
            
            lang: "" || navigator.language || navigator.systemLanguage || navigator.userLanguage,
            
            oauth: {
            
            
                client_secret: '0d352353407a32cee695d8ac619108e725919c57',
            
                client_id: '5c74c5e1b67e5a5adbdf'
            }});
        gitment.render('gitment-container');
      }

      
      function showGitment(){
        document.getElementById("gitment-display-button").style.display = "none";
        document.getElementById("gitment-container").style.display = "block";
        renderGitment();
      }
      
      </script>
    







  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
    
      flOptions = {};
      
          flOptions.iconStyle = "box";
      
          flOptions.boxForm = "horizontal";
      
          flOptions.position = "middleRight";
      
          flOptions.networks = "Weibo,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>

  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="https://cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  
 
</body>
</html>
